package com.newland.boss1.zxy.monitor;

import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.distribution.Histogram;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author : zhangxuyuan
 * @Project: springbootprometheus
 * @Package com.newland.boss1.zxy.monitor
 * @date Date : 2021年03月12日 17:04
 */
@Component
@Aspect
public class MethodMetricMonitor {


    @Autowired
    MeterRegistry meterRegistry;


    @Pointcut("@annotation(com.newland.boss1.zxy.monitor.MethodMetric)")
    public void pointcut() {}

    @Around("pointcut()")
    public Object process(ProceedingJoinPoint joinPoint) throws Throwable
    {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        MethodMetric annotation = method.getAnnotation(MethodMetric.class);
        System.out.println(annotation.name());
        Timer timer = Timer.builder(annotation.name()).tags(annotation.tag(),annotation.tag())
                .description(annotation.description())
                .register(meterRegistry);


        return timer.record(() -> {
            try {
                return joinPoint.proceed();
            } catch (Throwable throwable) {
                throw new IllegalStateException(throwable);
            }
        });

    }

}
